﻿using System;
using System.Diagnostics.CodeAnalysis;
using BootstrapBlazor.Components;
using iTeamyou.LTS.Core.Services;
using iTeamyou.LTS.Core.Models;
using Microsoft.AspNetCore.Components;
using NPOI.XWPF.UserModel;
using System.Linq;
using iTeamyou.LTS.UI.Utils;
using iTeamyou.LTS.UI.Models;
using System.Reflection.Emit;
using NPOI.SS.Formula.Functions;

namespace iTeamyou.LTS.UI.Pages.Archive.Supplier
{
	public partial class Index
	{
        [Parameter]
        public string? Token { get; set; }

        [Inject]
		[NotNull]
		private SharedService? SharedService { get; set; }

        [Inject]
        [NotNull]
        private SupplierService? SupplierService { get; set; }

        [Inject]
        [NotNull]
        private DialogService? DialogService { get; set; }

        [Inject]
        [NotNull]
        private MessageService? MessageService { get; set; }

        [Inject]
        [NotNull]
        private NavigationManager NavigationManager { get; set; }

        [Inject]
        [NotNull]
        private DownloadService? DownloadService { get; set; }

        public List<Core.Models.Supplier>? SelectedSuppliers { get; set; } = new();

        [Parameter]
        public Action? OnClose { get; set; }

        //public SearchModel? SearchModel { get; set; } = new();

        [NotNull]
        private IEnumerable<Core.Models.Supplier>? Suppliers { get; set; }

        private ITableSearchModel SupplierSearchModel { get; set; } = new SupplierSearchModel();

        [Inject] HttpContextAccessor HttpContextAccessor { get; set; }
        [Inject] protected IExcelHelper excelHelper { get; set; }
        [Inject] protected ILoginService<LoginUser>? loginService { get; set; }

        private static IEnumerable<int> PageItemsSource => new int[] { 10, 20, 50 };
        private string UserId { get; set; }
        public bool IsAutoRefresh { get; set; }
        private bool IsUnauth { get; set; }

        private static readonly string AppCode = "LTS_Supplier";
        private static readonly string PrivilegeCode = "[SUPPLIER]";

        protected override void OnInitialized()
        {
            var isDebug = bool.Parse(SharedService.GetConfig("IsDebug"));
            if (isDebug)
            {
                UserId = SharedService.GetConfig("DebugUser");
                IsUnauth = false;
            }
            else
                IsUnauth = !PageAuthAsync();

            base.OnInitialized();

            if (!IsUnauth)
            {
                SharedService.RefreshRequested += RefreshData;
                RefreshData();
            }
        }

        private bool PageAuthAsync()
        {
            var authToken = HttpContextAccessor.HttpContext.Request.Cookies["SSOToken"];

            if (!string.IsNullOrEmpty(Token))
            {
                try
                {
                    var cookieOptions = new CookieOptions() { Expires = DateTime.Now.AddDays(2) };
                    HttpContextAccessor.HttpContext.Response.Cookies.Append("SSOToken", Token, cookieOptions);
                }
                catch { }

                var segments = NavigationManager.Uri.Split('/');
                var redirectUrl = string.Join("/", segments.Take(segments.Length - 1));
                try
                {
                    NavigationManager.NavigateTo(redirectUrl, true, true);
                }
                catch (NavigationException) { }
                Token = string.Empty;
            }
            else if (string.IsNullOrEmpty(authToken) && string.IsNullOrEmpty(Token))
            {
                try
                {
                    NavigationManager.NavigateTo(SharedService.GetConfig("EKPLoginURL"), true);
                }
                catch (NavigationException) { }
                return false;
            }

            //var authToken = "83dfa37029393dbca8047ab0482ebd1b969d4c95b11b7a1f62b6dfb529a14d5f42d8559d1467e4b5f922e95c185cc800b6ae5c2bb90ba39efb01f297c2a94b274aa99fcc6a9e6678740f3d8a2bbfd3fe77a3fd6e04c04627a729a994c218398fa4c01a440d73de4a543989eeed9c6f0ceb638d539e06375e2f967ac3dca5c1a4";
            var currentUser = loginService.Login(AppCode, authToken);

            if (currentUser == null || string.IsNullOrEmpty(currentUser.Name))
            {
                //MessageService.Show(new MessageOption()
                //{
                //    Content = $"当前用户身份无效，请联系管理员",
                //    Icon = "fa-solid fa-circle-error",
                //    Color = Color.Danger,
                //    ShowDismiss = true,
                //    IsAutoHide = false
                //});
                try
                {
                    NavigationManager.NavigateTo(SharedService.GetConfig("EKPLoginURL"), true);
                }
                catch (NavigationException) { }
                return false;
            }
            else if (string.IsNullOrEmpty(currentUser.AppCode))
            {
                MessageService.Show(new MessageOption()
                {
                    Content = $"当前用户没有注册应用，请联系管理员",
                    Icon = "fa-solid fa-circle-error",
                    Color = Color.Danger,
                    ShowDismiss = true,
                    IsAutoHide = false
                });
                return false;
            }
            else if (!currentUser.Privilege.Contains(PrivilegeCode, StringComparison.CurrentCultureIgnoreCase))
            {
                MessageService.Show(new MessageOption()
                {
                    Content = $"当前用户没有访问权限，请联系管理员",
                    Icon = "fa-solid fa-circle-error",
                    Color = Color.Danger,
                    ShowDismiss = true,
                    IsAutoHide = false
                });
                return false;
            }
            UserId = currentUser.Name;
            //HttpContextAccessor.HttpContext.Response.Cookies.Append("SSOToken", Token);
            return true;
        }


        private async Task AddSupplier()
        {
            var op = new DialogOption()
            {
                Title = "新增供应商",
                ShowFooter = false
            };
            op.BodyTemplate = BootstrapDynamicComponent.CreateComponent<SupplierComponent>(new Dictionary<string, object?>
            {
                [nameof(SupplierComponent.OnClose)] = new Action(async () => await op.CloseDialogAsync()),
                [nameof(SupplierComponent.DocStatus)] = DocStatus.New,
                [nameof(SupplierComponent.UserId)] = UserId
            }).Render();
            op.IsScrolling = true;
            await DialogService.Show(op);
        }

        private async Task EditSupplier(Core.Models.Supplier supplier)
        {
            var op = new DialogOption()
            {
                Title = "编辑供应商",
                ShowFooter = false
            };
            op.BodyTemplate = BootstrapDynamicComponent.CreateComponent<SupplierComponent>(new Dictionary<string, object?>
            {
                [nameof(SupplierComponent.OnClose)] = new Action(async () => await op.CloseDialogAsync()),
                [nameof(SupplierComponent.DocStatus)] = DocStatus.Edit,
                [nameof(SupplierComponent.UserId)] = UserId,
                [nameof(SupplierComponent.SupplierModel)] = supplier
            }).Render();
            op.IsScrolling = true;
            await DialogService.Show(op);
        }

        private async Task EditSupplierBtn()
        {
            var op = new DialogOption()
            {
                Title = "编辑供应商",
                ShowFooter = false
            };
            op.BodyTemplate = BootstrapDynamicComponent.CreateComponent<SupplierComponent>(new Dictionary<string, object?>
            {
                [nameof(SupplierComponent.OnClose)] = new Action(async () => await op.CloseDialogAsync()),
                [nameof(SupplierComponent.DocStatus)] = DocStatus.Edit,
                [nameof(SupplierComponent.UserId)] = UserId,
                [nameof(SupplierComponent.SupplierModel)] = SelectedSuppliers.FirstOrDefault()
            }).Render();
            op.IsScrolling = true;
            await DialogService.Show(op);
        }

        private Task<QueryData<Core.Models.Supplier>> OnQueryAsync(QueryPageOptions options)
        {
            if (IsUnauth)
                return Task.FromResult(new QueryData<Core.Models.Supplier>() { });

            IsAutoRefresh = false;
            StateHasChanged();
            Suppliers = SupplierService.GetList();
            var searchModel = (SupplierSearchModel)options.SearchModel;
            //var searchModel = new SearchModel();

            // 处理快速搜索条件
            if (!string.IsNullOrEmpty(options.SearchText))
                Suppliers = Suppliers.Where(i => (i.Name?.Contains(options.SearchText, StringComparison.OrdinalIgnoreCase) ?? false)
                || (i.SId?.Contains(options.SearchText, StringComparison.OrdinalIgnoreCase) ?? false));

            // 处理自定义搜索条件
            if (!string.IsNullOrEmpty(searchModel.IdOrName))
                Suppliers = Suppliers.Where(i => (i.Name?.Contains(searchModel.IdOrName, StringComparison.OrdinalIgnoreCase) ?? false)
                || (i.SId?.Contains(searchModel.IdOrName, StringComparison.OrdinalIgnoreCase) ?? false));

            if (!string.IsNullOrEmpty(searchModel.IsLicenseExist))
            {
                switch(searchModel.IsLicenseExist)
                {
                    case "1":
                        Suppliers = Suppliers.Where(i => i.LicenseNum > 0);
                        break;
                    case "0":
                        Suppliers = Suppliers.Where(i => i.LicenseNum == 0);
                        break;
                    default:
                        break;
                }
            }

            if (searchModel.SearchDate != null && searchModel.SearchDate.Start != null)
                Suppliers = Suppliers.Where(i => i.CreatedOn >= searchModel.SearchDate.Start && i.CreatedOn <= searchModel.SearchDate.End);

            // 过滤
            var isFiltered = false;
            if (options.Filters.Any())
            {
                Suppliers = Suppliers.Where(options.Filters.GetFilterFunc<Core.Models.Supplier>());
                isFiltered = true;
            }

            // 排序
            var isSorted = false;
            if (!string.IsNullOrEmpty(options.SortName))
            {
                if (options.SortOrder == SortOrder.Asc)
                    Suppliers = Suppliers.OrderBy(g => SharedService.GetPropertyValue(g, options.SortName));
                else if (options.SortOrder == SortOrder.Desc)
                    Suppliers = Suppliers.OrderByDescending(g => SharedService.GetPropertyValue(g, options.SortName));
                else
                    Suppliers = Suppliers.OrderByDescending(g => g.LastModifiedOn);
                isSorted = true;
            }

            // 设置记录总数
            var total = Suppliers.Count();

            // 内存分页
            Suppliers = Suppliers.Skip((options.PageIndex - 1) * options.PageItems).Take(options.PageItems).ToList();

            // 扩展实体和属性转换查询
            foreach (var supplier in Suppliers)
            {
                supplier.SupplierLicenses = SupplierService.GetLicensesById(supplier.Id);
            }

            return Task.FromResult(new QueryData<Core.Models.Supplier>()
            {
                Items = Suppliers,
                TotalCount = total,
                IsSorted = isSorted,
                IsFiltered = isFiltered,
                IsSearch = options.CustomerSearches.Any() || !string.IsNullOrEmpty(options.SearchText),
                IsAdvanceSearch = options.CustomerSearches.Any()
            });
        }

        //private async Task Search()
        //{
        //    StateHasChanged();
        //    IEnumerable<Core.Models.Supplier> suppliers = SupplierService.GetList();
        //    //var searchModel = (SearchModel)options.SearchModel;

        //    // 处理自定义搜索条件
        //    if (!string.IsNullOrEmpty(SearchModel.IdOrName))
        //        suppliers = suppliers.Where(i => i.Name == SearchModel.IdOrName || i.Id == SearchModel.IdOrName);
        //    if (SearchModel.SearchDate != null && SearchModel.SearchDate.Start != null)
        //        suppliers = suppliers.Where(i => i.CreatedOn >= SearchModel.SearchDate.Start && i.CreatedOn <= SearchModel.SearchDate.End);

        //    Suppliers = suppliers.ToList();
        //    StateHasChanged();
        //}

        //private Task<QueryData<Core.Models.Supplier>> OnSearchModelQueryAsync(QueryPageOptions options)
        //{
        //    // 自定义了 SearchModel
        //    // 由于使用 SearchTemplate 自定义处理了。无法使用内置的 ToFilter 获得过滤条件

        //    // 处理模糊搜索
        //    IEnumerable<Core.Models.Supplier> items = SupplierService.GetList();
        //    if (!string.IsNullOrEmpty(options.SearchText))
        //    {
        //        items = items.Where(i => (i.Name?.Contains(options.SearchText, StringComparison.OrdinalIgnoreCase) ?? false)
        //        || (i.Id?.Contains(options.SearchText, StringComparison.OrdinalIgnoreCase) ?? false));
        //    }

        //    // 处理自定义搜索条件
        //    if (!string.IsNullOrEmpty(SearchModel.IdOrName))
        //    {
        //        items = items.Where(i => i.Name == SearchModel.IdOrName || i.Id == SearchModel.IdOrName);
        //    }
        //    if (SearchModel.CreateFrom != null)
        //    {
        //        items = items.Where(i => i.CreatedOn >= SearchModel.CreateFrom);
        //    }
        //    if (SearchModel.CreateTo != null)
        //    {
        //        items = items.Where(i => i.CreatedOn <= SearchModel.CreateTo);
        //    }

        //    // 设置记录总数
        //    var total = items.Count();
        //    // 内存分页
        //    items = items.Skip((options.PageIndex - 1) * options.PageItems).Take(options.PageItems).ToList();
        //    return Task.FromResult(new QueryData<Core.Models.Supplier>()
        //    {
        //        Items = items,
        //        TotalCount = total,
        //        IsSorted = true,
        //        IsFiltered = options.Filters.Any(),
        //        IsSearch = options.Searches.Any(),
        //        IsAdvanceSearch = options.AdvanceSearches.Any()
        //    });
        //}

        private async Task Export()
        {
            try
            {
                if (SelectedSuppliers.Count > 0)
                {
                    var exportList = SupplierService.GetExport(SelectedSuppliers);
                    var fileName = $"ExportSupplier_{DateTime.Now.ToString("yyMMddHHmmss")}.xls";
                    var filePathString = Path.Combine(SharedService.GetConfig("exportPath"), fileName);
                    var filePath = excelHelper.ExportToExcel(exportList, "Supplier", filePathString, ".xls");
                    using var stream = File.OpenRead(filePath);
                    await DownloadService.DownloadFromStreamAsync(fileName, stream);
                    await MessageService.Show(new MessageOption()
                    {
                        Content = "导出成功",
                        Icon = "fa-solid fa-circle-info",
                        Color = Color.Success,
                        ShowDismiss = true
                    });
                }
                else
                {
                    var exportList = SupplierService.GetExport();
                    var fileName = $"ExportSupplier_{DateTime.Now.ToString("yyMMddHHmmss")}.xls";
                    var filePathString = Path.Combine(SharedService.GetConfig("exportPath"), fileName);
                    var filePath = excelHelper.ExportToExcel(exportList, "Supplier", filePathString, ".xls");
                    using var stream = File.OpenRead(filePath);
                    await DownloadService.DownloadFromStreamAsync(fileName, stream);
                    await MessageService.Show(new MessageOption()
                    {
                        Content = "导出成功",
                        Icon = "fa-solid fa-circle-info",
                        Color = Color.Success,
                        ShowDismiss = true
                    });
                }
            }
            catch (FileNotFoundException)
            {
                await MessageService.Show(new MessageOption()
                {
                    Content = "导出时发生错误，请重试",
                    Icon = "fa-solid fa-circle-error",
                    Color = Color.Danger,
                    ShowDismiss = true
                });
            }
        }

        private async Task DeleteSuppliers(List<Core.Models.Supplier> suppliers)
        {
            SupplierService.Delete(suppliers);
            StateHasChanged();
            SharedService.CallRequestRefresh();
            await Task.CompletedTask;
            await MessageService.Show(new MessageOption()
            {
                Content = $"删除供应商成功，删除了{suppliers.Count}条记录",
                Icon = "fa-solid fa-circle-info",
                Color = Color.Success,
                ShowDismiss = true
            });
        }

        private Task SelectChanged(List<Core.Models.Supplier> SelectSuppliers)
        {
            SelectedSuppliers = SelectSuppliers;
            StateHasChanged();
            return Task.CompletedTask;
        }

        private void RefreshData()
        {
            IsAutoRefresh = true;
            StateHasChanged();
        }
    }
}

